package com.baosight.risk.web.freemarker;


import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import com.baosight.risk.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;

/**
 * @author 段永强
 *
 * word转换pdf
 */
public class AsposeWordToPDF {
    private static final Logger log = LoggerFactory.getLogger(AsposeWordToPDF.class);

    /**
     * word to pdf
     *
     * @param inPath  需要转换的 doc 文件地址
     * @param outPath 写入磁盘的pdf文件地址
     */
    public static void docToPdfWatermark(String inPath, String outPath) {
        if (StringUtils.isNotEmpty(inPath)){
            try {
                docToPdfWatermark(new FileInputStream(inPath), outPath);
            }catch (Exception e){
                log.error(e.getMessage());
            }
        }
    }

    public static void docToPdfWatermark(File file, String outPath) {
        if (file != null){
            try {
                docToPdfWatermark(new FileInputStream(file), outPath);
            }catch (Exception e){
                log.error(e.getMessage());
            }
        }
    }

    /**
     *服务器缺失word文档所需要的字体，会导致转换的pdf乱码
     */
    public static void docToPdfWatermark(InputStream in, String outPath) {
        //获取破解license
        getLicense();
        FileOutputStream os = null;
        try {
            // 新建一个空白pdf文档
            os = new FileOutputStream(outPath);
            log.info("新建一个空白pdf文档");
            // Address是将要被转化的word文档
            Document doc = new Document(in);
            log.info("开始转换文档");
            doc.save(os, SaveFormat.PDF);
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
            }
        }

    }

    /**
     * 获取license
     * @return boolean
     */
    public static boolean getLicense() {
        boolean result = false;
        InputStream is = null;
        try {
            is = AsposeWordToPDF.class.getResourceAsStream("/aspose/license.xml");
            License aposeLic = new License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            log.error(e.getMessage());
        } finally {
            if(is != null){
                try {
                    is.close();
                }catch (IOException e){
                    log.error(e.getMessage());
                }

            }
        }
        return result;
    }

    public static void main(String[] args) throws IOException {
        AsposeWordToPDF.docToPdfWatermark("C:\\Users\\VULCAN\\Downloads\\2019年三季度_中美贸易摩擦衍生风险_披露报告.doc",
                "C:\\Users\\VULCAN\\Downloads\\test.pdf");
    }
}
